﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

namespace Admin.NET.Core.Service;

/// <summary>
/// 系统数据库备份服务 🧩
/// </summary>
[ApiDescriptionSettings(Order = 255, Description = "数据库备份")]
public class SysDbBackupService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<SysUser> _sysUserRep;
    private readonly string backupDir;

    public SysDbBackupService(SqlSugarRepository<SysUser> sysUserRep)
    {
        _sysUserRep = sysUserRep;
        backupDir = Path.Combine(App.WebHostEnvironment.WebRootPath, "DbBackup");
    }

    /// <summary>
    /// 获取备份列表 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取备份列表")]
    public List<DbBackupOutput> GetList()
    {
        try
        {
            var fileList = Directory.GetFiles(backupDir);

            var dbBackupList = new List<DbBackupOutput>();
            foreach (var item in fileList)
            {
                var info = new FileInfo(item);
                dbBackupList.Add(new DbBackupOutput
                {
                    FileName = info.Name,
                    Size = info.Length,
                    CreateTime = info.CreationTime
                });
            }
            return dbBackupList;
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// 备份数据库 🔖
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    [DisplayName("备份数据库")]
    public async Task AddBackup()
    {
        await Backup();
    }

    /// <summary>
    /// 删除备份 🔖
    /// </summary>
    /// <param name="fileName"></param>
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    [DisplayName("删除备份")]
    public void DeleteBackup([FromQuery] string fileName)
    {
        var path = Path.Combine(backupDir, fileName);
        File.Delete(path);
    }

    /// <summary>
    /// 备份数据库
    /// </summary>
    /// <returns></returns>
    [NonAction]
    public async Task Backup()
    {
        await Task.Run(() =>
        {
            var options = App.GetOptions<DbConnectionOptions>();
            foreach (var option in options.ConnectionConfigs)
            {
                var configId = option.ConfigId == null || string.IsNullOrWhiteSpace(option.ConfigId.ToString())
                    ? SqlSugarConst.MainConfigId : option.ConfigId.ToString();

                // 备份mysql  其他数据库自行扩展
                if (option?.DbType == SqlSugar.DbType.MySql)
                {
                    var path = Path.Combine(backupDir, $"{configId}-{DateTime.Now:yyyyMMddHHmmss}.sql");
                    _sysUserRep.Context.DbMaintenance.BackupDataBase(_sysUserRep.Context.Ado.Connection.Database, path);
                }
            }
        });
    }

    /// <summary>
    /// 删除过期备份文件
    /// </summary>
    /// <param name="day">过期天数</param>
    [NonAction]
    public void DeleteExpiredDbFile(int day = 7)
    {
        var list = Directory.GetFiles(backupDir);
        foreach (var item in list)
        {
            var info = new FileInfo(item);
            if (info.CreationTime.AddDays(day) < DateTime.Now)
            {
                try
                {
                    File.Delete(item);
                }
                catch (Exception)
                {
                    continue;
                }
            }
        }
    }
}